from django.core.paginator import PageNotAnInteger
from django.shortcuts import render
from django.views.generic.base import View
from pure_pagination import Paginator

from apps.blogmessage.models import BlogMessage, BlogTag
from apps.users.models import UserProfile


# Create your views here.




class BlogMessageView(View):

    def get(self, request, blog_id ,*args, **kwargs):
        user = UserProfile.objects.get(id=1)
        blog_message = BlogMessage.objects.get(id=blog_id)
        message_all = BlogMessage.objects.all()
        tag_id = blog_message.tag.id
        message_tag_all = BlogMessage.objects.filter(tag=int(tag_id)).order_by('-add_time')[0:5]
        new_messages = message_all.order_by('-add_time')[0:10]
        tags = BlogTag.objects.all()
        blog_message.click_nums += 1
        blog_message.save()
        try:
            next_message = BlogMessage.objects.get(id=(blog_id+1))
        except:
            next_message = False
        try:
            previous_message = BlogMessage.objects.get(id=(blog_id-1))
        except:
            previous_message = False
        return render(request, 'blogmessage.html', {
            'user': user,
            'blog_message':blog_message,
            'next_message':next_message,
            'previous_message':previous_message,
            'new_messages': new_messages,
            'tags': tags,
            'message_tag_all': message_tag_all
        })

class BlogTagMessageView(View):

    def get(self, request, tag_id ,*args, **kwargs):
        user = UserProfile.objects.get(id=1)
        message_all_r = BlogMessage.objects.all()
        message_all = BlogMessage.objects.filter(tag=int(tag_id))
        new_messages = message_all_r.order_by('-add_time')[0:10]
        tags = BlogTag.objects.all()
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        # 对课程机构数据进行分页
        p = Paginator(message_all, per_page=10, request=request)
        messages = p.page(page)

        return render(request, 'index.html', {
            'user': user,
            'messages': messages,
            'new_messages': new_messages,
            'tags': tags
        })


